"""

A small Test application to show how to use Flask-MQTT.

"""
import threading
import eventlet
import json
from flask import Flask, render_template,request
from flask_mqtt import Mqtt
from flask_socketio import SocketIO
from flask_bootstrap import Bootstrap

eventlet.monkey_patch()

app = Flask(__name__)
app.config['SECRET'] = 'my secret key'
app.config['TEMPLATES_AUTO_RELOAD'] = True
app.config['MQTT_BROKER_URL'] = 'localhost'
app.config['MQTT_BROKER_PORT'] = 1883
app.config['MQTT_USERNAME'] = ''
app.config['MQTT_PASSWORD'] = ''
app.config['MQTT_KEEPALIVE'] = 60
app.config['MQTT_TLS_ENABLED'] = False

mqtt = Mqtt(app)
socketio = SocketIO(app)
bootstrap = Bootstrap(app)

# mqtt主题订阅
topics = ["53010000","4e010001","4e010001"]
# timers = []
for t in topics:
    mqtt.subscribe(topic=t, qos=0)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/serial_recv', methods=['GET', 'POST'])
def serial_recv():
    print("ajax访问"*5)
    data = request.json
    print(type(data))
    # data = ser.read(100)
    # if len(data) > 0:
        # print(data)
        # ser.write(data)
    return "ok"

@socketio.on('publish')
def handle_publish(json_str):
    print("推送消息")
    data = json.loads(json_str)
    mqtt.publish(data['topic'], data['message'])

@socketio.on('subscribe')
def handle_subscribe(json_str):
    data = json.loads(json_str)
    print(data)
    mqtt.subscribe(data['topic'])

@mqtt.on_message()
def handle_mqtt_message(client, userdata, message):
    data = dict(
        topic=message.topic,
        payload=message.payload.decode()
    )
    print("接收到mqtt消息")
    # ser.serial.write(message.payload)
    socketio.emit('mqtt_message', data=data)
    socketio.emit('client', data = '{"topic": "' + '4e010001' + '", "message": "' + "测试" + '", "qos": ' + '0' + '}')


@mqtt.on_log()
def handle_logging(client, userdata, level, buf):
    print(level, buf)


if __name__ == '__main__':
    app.run( host='0.0.0.0', port=5000)
    # socketio.run(app, host='0.0.0.0', port=5000, debug=True)
